<!-- filename: pages/public-playlist-detail/public-playlist-detail.vue (最终正确版) -->
<template>
  <view class="page-container" @click="handlePageClick">
    <Header @open-auth-modal="isAuthModalVisible = true" />
    <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

    <!-- 【新增】评论模态框 -->
    <CommentModal
      v-if="isCommentModalVisible"
      target-type="playlist"
      :target-id="playlistId"
      :highlight-parent-id="highlightParentId"
      :highlight-comment-id="highlightCommentId"
      @close="handleCommentModalClose"
    />

    <div class="content-wrapper" style="padding-top: 60px;">
      <view v-if="isLoading" class="loading-state">正在加载...</view>
      <view v-else-if="error" class="error-state">{{ error }}</view>
      
      <view v-else-if="playlistInfo" class="playlist-detail-content">
        
        <header class="page-header">
          <view class="cover-placeholder">
             <image v-if="playlistInfo.cover_url" :src="playlistInfo.cover_url" class="cover-image" mode="aspectFill" />
             <svg v-else width="40" height="40" viewBox="0 0 24 24" fill="currentColor"><path d="M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 5h-3v5.5c0 1.38-1.12 2.5-2.5 2.5S10 13.88 10 12.5s1.12-2.5 2.5-2.5c.57 0 1.08.19 1.5.51V5h4v2zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6z"/></svg>
          </view>
          <div class="header-info">
            <h1 class="playlist-name">{{ playlistInfo.name }}</h1>
            <div class="creator-and-stats">
              <view class="creator-info" @click="navigateToUserProfile(playlistInfo.user_id)">
                <!-- 优先显示头像图片 -->
                <image
                  v-if="playlistInfo.avatar_url"
                  :src="playlistInfo.avatar_url"
                  class="avatar-image"
                  mode="aspectFill"
                />
                <!-- 备用方案：显示首字母 -->
                <view v-else class="avatar-placeholder">
                  {{ (playlistInfo.username || 'U').charAt(0).toUpperCase() }}
                </view>
                <span class="username">{{ playlistInfo.username }}</span>
              </view>
              <span class="song-count-header">{{ `共 ${allSongsInPlaylist.length} 首歌` }}</span>
            </div>
          </div>
        </header>

        <view class="meta-info">
          <span>创建于: {{ playlistInfo.published_at }}</span>
          <span> • </span>
          <span>更新于: {{ playlistInfo.updated_at }}</span>
        </view>

        <view class="playlist-description">
          <p>{{ playlistInfo.description || '暂无简介' }}</p>
        </view>

        <div class="actions-bar">
          <div class="action-btn" :class="{ 'active': isCollected }" @click="handleCollectClick">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
            <span>{{ isCollected ? '已点赞' : '点赞' }} ({{ collectionCount }})</span>
          </div>
          <div class="action-btn" @click="isCommentModalVisible = true">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4-.01-18zM18 14H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/></svg>
            <span>评论 ({{ playlistInfo.comments_count || 0 }})</span>
          </div>
        </div>
        
        <SearchBar 
          ref="searchBarRef" 
          @search="handleSearch"
          @focus="handleSearchBarFocus"
          search-context="local"
          :local-data="allSongsInPlaylist"
        />

        <!-- 【新增】ListControls 组件 -->
        <ListControls
          :pagination="pagination"
          :current-sort="currentSort"
          context="public-playlist" 
          @update:page="handlePageChange"
          @update:sort="handleSortChange"
        />

        <main class="song-list-container">
          <view v-if="songs.length === 0" class="empty-state">歌单里还没有歌曲</view>
          <view v-else class="song-list-wrapper">
            <SongCard
              v-for="song in songs"
              :key="song.id"
              :ref="(el) => setSongCardRef(song.id, el)"
              :song="song"
              @play="handlePlaySong"
              @filter="handleSongCardFilter"
              @menuToggled="handleMenuToggled"
            />
          </view>
        </main>
      </view>
    </div>

    <Player v-if="playerStore.showPlayer" />
  </view>
</template>


<script setup>
import { ref, onBeforeUpdate, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { usePlayerStore } from '@/store/player';
import { request } from "@/utils/request"; // 【核心修改1】

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';
import Player from '@/components/Player.vue';
import SongCard from '@/components/SongCard/SongCard.vue';
import SearchBar from '@/components/SearchBar/SearchBar.vue';
import CommentModal from '@/components/CommentModal/CommentModal.vue';
import ListControls from '@/components/ListControls/ListControls.vue'; // 导入 ListControls

const authStore = useAuthStore();
const playerStore = usePlayerStore();
const isAuthModalVisible = ref(false);

const playlistInfo = ref(null);
const songs = ref([]);
const allSongsInPlaylist = ref([]);
const isLoading = ref(true);
const error = ref('');
let playlistId = null;

const isCollected = ref(false);
const collectionCount = ref(0);
const isCommentModalVisible = ref(false);
const highlightParentId = ref(null);
const highlightCommentId = ref(null);

const searchBarRef = ref(null);
const songCardRefs = ref({});
const currentSort = ref('sort_order');
const openedMenuCardId = ref(null);
const pagination = ref({ current_page: 1, total_pages: 1, total_items: 0 }); // pagination 保持


// --- 【核心修改2】重写所有 API 请求函数 ---

const fetchPublicPlaylistDetail = () => {
  return new Promise(async (resolve, reject) => {
    isLoading.value = true;
    error.value = '';
    
    try {
      const data = await request({
        url: `/api/public/playlists/${playlistId}?sort_by=${currentSort.value}`,
        method: 'GET'
      });
      playlistInfo.value = data.info;
      allSongsInPlaylist.value = [...data.songs];
      songs.value = [...data.songs];
      isCollected.value = data.info.is_collected_by_user;
      collectionCount.value = data.info.collection_count;
      uni.setNavigationBarTitle({ title: data.info.name });
      resolve();
    } catch (err) {
      error.value = err?.data?.error || '加载歌单失败';
      reject(err);
    } finally {
      isLoading.value = false;
    }
  });
};

const handleCollectClick = async () => {
  if (!authStore.isLoggedIn) {
    isAuthModalVisible.value = true;
    return;
  }
  
  const originalIsCollected = isCollected.value;
  isCollected.value = !isCollected.value;
  collectionCount.value += isCollected.value ? 1 : -1;

  try {
    const data = await request({
      url: `/api/public/playlists/${playlistId}/collect`,
      method: isCollected.value ? 'POST' : 'DELETE',
    });
    isCollected.value = data.is_collected_by_user;
    collectionCount.value = data.collection_count;
  } catch (error) {
    isCollected.value = originalIsCollected;
    collectionCount.value += originalIsCollected ? 1 : -1;
    if (error.statusCode !== 401) {
      uni.showToast({ title: "操作失败，请重试", icon: 'error' });
    }
  }
};


// --- 无需修改的函数 ---
onLoad((options) => {
  playlistId = options.id;
  if (!playlistId) {
    error.value = '无效的歌单ID';
    isLoading.value = false;
    return;
  }
  
  fetchPublicPlaylistDetail().then(() => {
    if (options.action === 'find_comment') {
      highlightParentId.value = options.parent_id ? parseInt(options.parent_id, 10) : null;
      highlightCommentId.value = options.comment_id ? parseInt(options.comment_id, 10) : null;
      nextTick(() => {
        isCommentModalVisible.value = true;
      });
    }
  });
});

const navigateToUserProfile = (userId) => {
  if (userId === null || userId === undefined) {
    uni.showToast({ title: '无法查看该用户', icon: 'error' });
    return;
  }
  if (!authStore.isLoggedIn) {
    isAuthModalVisible.value = true;
    return;
  }
  if (authStore.user && authStore.user.id === userId) {
    uni.switchTab({ url: '/pages/profile/profile' });
    return;
  }
  uni.navigateTo({ url: `/pages/user-profile/user-profile?id=${userId}` });
};

const handleCommentModalClose = () => {
  isCommentModalVisible.value = false;
  fetchPublicPlaylistDetail();
};

const handleSearch = (payload) => {
  const keywords = payload.value.trim().toLowerCase().split(' ').filter(Boolean);
  if (keywords.length === 0) {
    songs.value = [...allSongsInPlaylist.value];
  } else {
    songs.value = allSongsInPlaylist.value.filter(song => {
      const songText = [ song.title, song.cover_artists, song.original_artists, song.language_name, song.status_name, song.cover_date.replace(/-/g, '') ].join(' ').toLowerCase();
      return keywords.every(kw => songText.includes(kw));
    });
  }
};

const handleSortChange = (newSort) => {
  currentSort.value = newSort;
  fetchPublicPlaylistDetail();
};

const handlePlaySong = (songId) => {
  playerStore.setPlaylistAndPlay(songs.value, songId);
};

onBeforeUpdate(() => {
  songCardRefs.value = {};
});
const setSongCardRef = (id, el) => {
  if (el) songCardRefs.value[id] = el;
};
const handleSongCardFilter = (searchTerm) => {
  if (searchBarRef.value) {
    searchBarRef.value.setSearchTextAndExecute(searchTerm);
  }
};
const handleMenuToggled = (payload) => {
  const { id, isOpen } = payload;
  if (isOpen) {
    if (openedMenuCardId.value && openedMenuCardId.value !== id) {
      const oldCard = songCardRefs.value[openedMenuCardId.value];
      if (oldCard) oldCard.closeMenu();
    }
    openedMenuCardId.value = id;
  } else if (openedMenuCardId.value === id) {
    openedMenuCardId.value = null;
  }
};
const handlePageClick = () => {
  if (searchBarRef.value) {
    searchBarRef.value.closeSearchResults();
  }
  if (openedMenuCardId.value) {
    const card = songCardRefs.value[openedMenuCardId.value];
    if (card) card.closeMenu();
  }
};
const handleSearchBarFocus = () => {
  if (openedMenuCardId.value) {
    const card = songCardRefs.value[openedMenuCardId.value];
    if (card) card.closeMenu();
  }
};
const handlePageChange = () => {}; // 占位
</script>

<style scoped lang="scss">
/* --- 页面基础布局 --- */
.page-container {
  display: flex;
  justify-content: center;
  width: 100%;
  min-height: 100vh;
  background-color: #fff; /* 背景改为白色 */
}
.content-wrapper {
  width: 100%;
  max-width: 800px;
  background-color: #ffffff;
  margin: 0 auto; /* 实现水平居中 */
}
.loading-state, .error-state, .empty-state {
  text-align: center; padding: 80px 20px; color: #888;
}

/* --- 页面特有样式 --- */
.playlist-detail-content { padding-bottom: 150px; }
.page-header {
  display: flex; align-items: flex-start; gap: 20px;
  padding: 20px;
}
.cover-placeholder {
  width: 120px; height: 120px; flex-shrink: 0; border-radius: 8px;
  display: flex; align-items: center; justify-content: center;
  background-color: #f0f0f0; color: #ccc;
  overflow: hidden; /* 确保图片不超出圆角 */
}
.cover-image {
  width: 100%;
  height: 100%;
}
.header-info {
  display: flex; flex-direction: column; min-width: 0;
}
.playlist-name {
  font-size: 24px; font-weight: bold; margin-bottom: 12px;
}
/* 【UI修正】 */
.creator-and-stats {
  display: flex;
  flex-direction: column; /* 让子元素垂直排列 */
  align-items: flex-start; /* 左对齐 */
  gap: 8px; /* 增加垂直间距 */
}
.creator-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}
.avatar-placeholder,
.avatar-image { // <-- 将 avatar-image 添加到选择器中
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: #007aff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}
.avatar-image {
  background-color: #f0f0f0; // 图片加载前的占位色
}
.username {
  font-size: 14px;
  font-weight: 500;
}
.song-count-header {
  font-size: 14px; /* 【修改】增大字号 */
  color: #888;
}
.meta-info, .playlist-description {
  padding: 0 20px 15px 20px;
  font-size: 12px;
  color: #888;
}
.playlist-description p {
  font-size: 14px; color: #666; line-height: 1.6;
}

/* 操作按钮条 */
.actions-bar {
  display: flex;
  justify-content: space-around;
  padding: 10px 20px;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 15px;
}
.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f5f5f5;
  font-size: 14px;
  cursor: pointer;
  &.active {
    background-color: #ffe1e8;
    color: #e5245e;
  }
}

.song-list-container {
  padding: 0 20px;
}
.song-count {
  font-size: 14px; color: #888; margin-bottom: 10px;
}
</style>